package cn.pop.hsp_system_v2.Util;


import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class FileUtil {
    @org.springframework.beans.factory.annotation.Value("${file.path}")
    private String dirpath;
    public String uploadFile(MultipartFile file) throws Exception {
        // 首先校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp");
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (imageType.contains(fileSuffix)) {
            // 只有当满足图片格式时才进来，重新赋图片名，防止出现名称重复的情况
            String newFileName = System.currentTimeMillis() + "." + fileSuffix;
            String path = File.separator + newFileName;
            File destFile = new File(this.dirpath + path);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // 返回上传的文件名
                return newFileName;
            } catch (IOException e) {
                return null;
            }
        } else {
            // 非法文件
            throw new Exception("the picture's suffix is illegal");
        }
    }

    public Date getdate(){
        Date now_time=new Date();
        return now_time;
    }

}
